<template>
  <div class="p-6">
    <!-- 工具栏 -->
    <div class="mb-4">
      <a-space>
        <a-input
          v-model="queryParams.keyword"
          placeholder="请输入分类名称或编码"
          allow-clear
          @press-enter="fetchList"
        />
        <a-select
          v-model="queryParams.status"
          placeholder="状态"
          allow-clear
          @change="fetchList"
        >
          <a-option :value="1">启用</a-option>
          <a-option :value="0">禁用</a-option>
        </a-select>
        <a-button type="primary" @click="handleAdd">
          <template #icon><icon-plus /></template>
          新增分类
        </a-button>
      </a-space>
    </div>

    <!-- 表格 -->
    <a-table
      :data="categoryList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
    >
      <template #columns>
        <a-table-column title="分类名称" data-index="name" />
        <a-table-column title="分类编码" data-index="code" />
        <a-table-column title="分类级别" data-index="level" />
        <a-table-column title="上级分类" data-index="parentName" />
        <a-table-column title="排序" data-index="sort" />
        <a-table-column title="状态" data-index="status">
          <template #cell="{ record }">
            <a-tag :color="record.status === 1 ? 'green' : 'red'">
              {{ record.status === 1 ? '启用' : '禁用' }}
            </a-tag>
          </template>
        </a-table-column>
        <a-table-column title="创建时间" data-index="createdAt" />
        <a-table-column title="操作">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" @click="handleView(record)">查看</a-button>
              <a-popconfirm
                content="确认删除该分类吗？"
                @ok="handleDelete(record)"
              >
                <a-button type="text" status="danger">删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </a-table-column>
      </template>
    </a-table>

    <!-- 新增/查看弹窗 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitleText"
      @cancel="closeModal"
      @before-ok="handleSubmit"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        @submit="handleSubmit"
      >
        <a-form-item field="name" label="分类名称" required>
          <a-input
            v-model="formData.name"
            :disabled="isView"
            placeholder="请输入分类名称"
          />
        </a-form-item>
        <a-form-item field="code" label="分类编码" required>
          <a-input
            v-model="formData.code"
            :disabled="isView"
            placeholder="请输入分类编码"
          />
        </a-form-item>
        <a-form-item field="level" label="分类级别" required>
          <a-select
            v-model="formData.level"
            :disabled="isView"
            placeholder="请选择分类级别"
            @change="handleLevelChange"
          >
            <a-option :value="1">一级分类</a-option>
            <a-option :value="2">二级分类</a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="parentId" label="上级分类" required>
          <a-select
            v-model="formData.parentId"
            :disabled="isView || formData.level === 1"
            placeholder="请选择上级分类"
          >
            <a-option
              v-for="category in parentCategories"
              :key="category.categoryId"
              :value="category.categoryId"
            >
              {{ category.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="sort" label="排序" required>
          <a-input-number
            v-model="formData.sort"
            :disabled="isView"
            placeholder="请输入排序号"
            :min="0"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import type { FormInstance } from '@arco-design/web-vue'
import type { EquipmentCategory, CategoryQuery, CategoryCreateDTO } from '@/types/device'
import { getCategoryList, createCategory, deleteCategory, getCategoryById } from '@/services/deviceCategory'

const loading = ref(false)
const categoryList = ref<EquipmentCategory[]>([])
const modalVisible = ref(false)
const isView = ref(false)
const formRef = ref<FormInstance>()
const modalTitleText = ref('新增分类')

const queryParams = reactive<CategoryQuery>({
  page: 1,
  size: 10,
  keyword: '',
  status: undefined,
  parentId: undefined
})

const pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: true,
  showJumper: true,
  showPageSize: true,
  pageSizeOptions: [10, 20, 50, 100]
})

const formData = reactive<CategoryCreateDTO>({
  name: '',
  code: '',
  level: 1,
  parentId: 0,
  sort: 0
})

const formRules = {
  name: [{ required: true, message: '请输入分类名称' }],
  code: [{ required: true, message: '请输入分类编码' }],
  level: [{ required: true, message: '请选择分类级别' }],
  parentId: [{ required: true, message: '请选择上级分类' }],
  sort: [{ required: true, message: '请输入排序号' }]
}

const modalTitle = computed(() => isView.value ? '查看分类' : '新增分类')

// 父分类列表（一级分类）
const parentCategories = computed(() => {
  return categoryList.value.filter(item => item.level === 1)
})

// 获取列表数据
const fetchList = async () => {
  loading.value = true
  try {
    const res = await getCategoryList(queryParams)
    console.log('获取分类列表响应:', res)
    
    const { data: response } = res
    if (response.code === 1 && response.data) {
      categoryList.value = response.data.records
      pagination.total = response.data.total
    } else {
      Message.error(response.msg || '获取列表失败')
    }
  } catch (error: any) {
    console.error('获取设备分类列表失败:', error)
    Message.error('获取设备分类列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handlePageChange = (current: number) => {
  queryParams.page = current
  fetchList()
}

// 新增分类
const handleAdd = () => {
  isView.value = false
  modalTitleText.value = '新增分类'
  modalVisible.value = true
  
  // 重置表单数据
  Object.assign(formData, {
    name: '',
    code: '',
    level: 1,
    parentId: 0,
    sort: 1
  })
}

// 查看分类
const handleView = (record: EquipmentCategory) => {
  isView.value = true
  modalTitleText.value = '查看分类'
  modalVisible.value = true
  Object.assign(formData, record)
}

// 删除分类
const handleDelete = async (record: EquipmentCategory) => {
  try {
    const res = await deleteCategory(record.categoryId)
    console.log('删除分类响应:', res)
    
    const { data: response } = res
    if (response.code === 1) {
      Message.success('删除成功')
      fetchList()
    } else {
      Message.error(response.msg || '删除失败')
    }
  } catch (error: any) {
    console.error('删除设备分类失败:', error)
    Message.error('删除失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (isView.value) {
    closeModal()
    return
  }
  
  try {
    await formRef.value?.validate()
    
    // 验证分类级别和父分类的关系
    if (formData.level === 1) {
      formData.parentId = 0
    } else if (formData.level === 2) {
      if (formData.parentId === 0) {
        Message.error('二级分类必须选择上级分类')
        return
      }
      // 验证选择的父分类是否存在且是一级分类
      const parent = parentCategories.value.find(item => item.categoryId === formData.parentId)
      if (!parent) {
        Message.error('选择的上级分类不存在或不是一级分类')
        return
      }
    }
    
    console.log('发送的数据:', formData)
    const res = await createCategory(formData)
    console.log('创建分类响应:', res)
    
    const { data: response } = res
    if (response.code === 1) {
      Message.success('创建成功')
      closeModal()
      fetchList()
    } else {
      Message.error(response.msg || '创建失败')
    }
  } catch (error: any) {
    console.error('创建设备分类失败:', error)
    Message.error('创建失败，请检查表单数据')
  }
}

// 监听分类级别变化
const handleLevelChange = (value: any) => {
  const level = Number(value)
  if (level === 1) {
    formData.parentId = 0
  } else {
    // 如果是二级分类且没有选择父分类，默认选择第一个一级分类
    if (formData.parentId === 0 && parentCategories.value.length > 0) {
      formData.parentId = parentCategories.value[0].categoryId
    }
  }
}

// 关闭弹窗
const closeModal = () => {
  modalVisible.value = false
  formRef.value?.resetFields()
}

// 初始化
onMounted(() => {
  fetchList()
})
</script> 